import { makeAutoObservable } from 'mobx';
import { Model, ModelFormValues, ModelType, ModelProvider, AuthType, ModelStatus} from './modelTypes';
import { getModelList, createModel, updateModel, getInfo, deleteModel } from '../../../../apis/backhub/model';

// 默认模型数据
const defaultModels: Model[] = [
  // 大语言模型
];

class ModelStore {
  models: Model[] = defaultModels;
  modalVisible = false; // 弹窗显示状态
  editingModel: Model | undefined = undefined; // 当前编辑的模型，undefined表示新建
  loading = false;

  constructor() {
    makeAutoObservable(this);
  }

  // 获取模型列表
  fetchModels = async () => {
    this.loading = true;
    try {
      // 这里可以添加实际的 API 调用
      const response = await getModelList();
      this.models = (response as any)?.data;
    } catch (error) {
      console.error('获取模型列表失败:', error);
    } finally {
      this.loading = false;
    }
  };

  //获取模型
  getModel = async (id: string) => {
    try {
      this.loading = true;
      const response = await getInfo(id);
      this.editingModel = (response as any).data;
      return this.editingModel; // 返回获取到的用户数据
    } catch (error) {
      console.error('获取用户失败:', error);
      throw error;
    } finally {
      this.loading = false;
    }
  };

  // 显示创建弹窗
  showCreateModal = () => {
    this.editingModel = undefined;
    this.modalVisible = true;
  };

  // 显示编辑弹窗
  showEditModal = (model: Model) => {
    this.getModel(model.id);
    this.modalVisible = true;
  };

  // 隐藏弹窗
  hideModal = () => {
    this.modalVisible = false;
    this.editingModel = undefined;
  };

  // 保存模型
  saveModel = async (values: ModelFormValues) => {
    try {
      if (this.editingModel && this.editingModel.id) {
        // 更新现有模型
        const index = this.models.findIndex(m => m.id === this.editingModel?.id);
        if (index !== -1) {
          this.models[index] = {
            ...this.models[index],
            ...values,
            updateTime: new Date().toISOString()
          };
        }
        await updateModel(this.editingModel.id, values);
      } else {
        // 创建新模型
        const newModel: Model = {
          ...values,
          id: (this.models.length + 1).toString(),
          createTime: new Date().toISOString(),
          updateTime: new Date().toISOString(),
          status: ModelStatus.ACTIVE,
          authType: AuthType.API_KEY
        };
        await createModel(values);
      }
      this.hideModal();
      this.fetchModels();
    } catch (error) {
      console.error('保存模型失败:', error);
    }
  };

  // 删除模型
  deleteModel = async (id: string) => {
    try {
      await deleteModel(id);
      this.fetchModels();
    } catch (error) {
      console.error('删除模型失败:', error);
    }
  };
}

export const modelStore = new ModelStore();